﻿namespace TfsExtensions.Build.Controls
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using Microsoft.TeamFoundation.Client;
    using Microsoft.TeamFoundation.Framework.Client;
    using System.Collections.ObjectModel;
    using Microsoft.TeamFoundation.Framework.Common;
    using Microsoft.TeamFoundation;
    using System.Net;
    using System.Diagnostics;
    using Microsoft.TeamFoundation.Build.Client;
    using Microsoft.TeamFoundation.VersionControl.Client;
    using System.IO;
    using System.Reflection;
    using Microsoft.TeamFoundation.Server;
    using TfsExtensions.Build.Controls;

    class TfsHelper
    {

        public Workspace GetWorkspace(string localPath, VersionControlServer sourceControl)
        {
            Workspace workspace = sourceControl.GetWorkspace(localPath);
            return workspace;
        }

        public Workspace CreateWorkspace(string workspaceName, string serverPath, string localpath, TfsTeamProjectCollection teamFoundationServer, VersionControlServer sourceControl)
        {
            Workspace workspace = sourceControl.CreateWorkspace(workspaceName, teamFoundationServer.AuthorizedIdentity.GetAttribute("userName", "administrator"));
            WorkingFolder folder = new WorkingFolder(serverPath, localpath);

            workspace.CreateMapping(folder);
            workspace.Get();
            return workspace;
        }

        public void CheckoutOrAddFile(string workspaceLocalFile, Workspace workspace, string newFile, bool isPath, VersionControlServer sourceControl)
        {
            if (!string.IsNullOrEmpty(workspaceLocalFile) && workspace != null)
            {
                var serverPath = workspace.TryGetServerItemForLocalItem(workspaceLocalFile);
                if (!String.IsNullOrEmpty(serverPath) && sourceControl.ServerItemExists(serverPath, ItemType.Any))
                {
                    workspace.PendEdit(workspaceLocalFile, RecursionType.None);
                    if (isPath)
                    {
                        File.Copy(newFile, workspaceLocalFile, true);
                    }
                    else
                    {
                        File.WriteAllText(workspaceLocalFile, newFile);
                    }
                }
                else
                {
                    if (isPath)
                    {
                        File.Copy(newFile, workspaceLocalFile, true);
                    }
                    else
                    {
                        File.WriteAllText(workspaceLocalFile, newFile);
                    }
                    workspace.PendAdd(workspaceLocalFile, true);
                }
            }
        }

        public static void CheckInChanges(Workspace workspace, string checkInNote)
        {
            if (workspace != null)
            {
                PendingChange[] pendingChanges = workspace.GetPendingChanges();

                if (pendingChanges.Length > 0)
                {
                    workspace.CheckIn(pendingChanges, checkInNote);
                }
            }
            else
            {
                throw new ArgumentNullException("workspace", "workSpace is null while calling TFSHelper.CheckInChanges.");
            }
        }

        public void DeleteWorkspace(string workspaceName, string localpath, TfsTeamProjectCollection teamFoundationServer, VersionControlServer sourceControl)
        {
            sourceControl.DeleteWorkspace(workspaceName, teamFoundationServer.AuthorizedIdentity.GetAttribute("userName", "administrator"));
            IOHelper.DeleteReadOnlyDirectory(localpath);
        }

        public void GetTeamFoundationServerConnection(string tfsServerName, IWin32Window parentWindow, out TfsTeamProjectCollection tfs,out VersionControlServer sourceControl)
        {
            tfs = null;
            RegisteredProjectCollection registeredProject = null;
            ICredentialsProvider uiCredentialProvider = new UICredentialsProvider(parentWindow);

            try
            {
                RegisteredProjectCollection[] collections = RegisteredTfsConnections.GetProjectCollections();
                if (collections != null)
                {
                    foreach (RegisteredProjectCollection collection in collections)
                    {
                        Debug.WriteLine(String.Format("{0} - {1}", collection.Name, collection.Uri));
                        if (String.Compare(tfsServerName, collection.Name) == 0)
                        {
                            registeredProject = collection;
                        }

                    }
                }

                tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(registeredProject, uiCredentialProvider);
                tfs.Authenticate();
            }
            catch
            {
                tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(registeredProject, uiCredentialProvider);
                try
                {
                    tfs.Authenticate();
                }
                catch
                {
                    tfs = null;
                }
            }

            if (tfs != null)
            {
                sourceControl = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
            }
            else
            {
                sourceControl = null;
            }
        }
    }
}
